﻿namespace BM.Tools.WebControls.MForm.Controls.ValueFormatters
{
    using System;
    using System.Globalization;

    /// <summary>
    /// A formatter used to format the numbers
    /// </summary>
    public class NumberFormatter : StringFormatter
    {
        /// <summary>
        /// Gets or sets the number format. The number format must be compatible to the one defined in the <see cref="decimal.ToString(string)"/> method.
        /// </summary>
        public string NumberFormat
        {
            get;
            set;
        }

        /// <summary>
        /// This method is used to format the numbers
        /// </summary>
        /// <param name="value">
        /// The value.
        /// </param>
        /// <returns>
        /// the formatted string
        /// </returns>
        public override string Format(string value)
        {
            try
            {
                var number = Convert.ToDecimal(value, CultureInfo.InvariantCulture);
                return number.ToString(NumberFormat, CultureInfo.InvariantCulture);
            } 
            catch (FormatException)
            {
                return value;
            }
            catch (OverflowException)
            {
                return value;
            }
        }
    }
}
